package com.asiainfo.indb.view;

import com.asiainfo.indb.PanelUtil;
import com.asiainfo.indb.model.FileGather;
import com.asiainfo.indb.model.InDbGather;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

/**
 * 文件选择
 *
 * @author zym
 * @date 2019-10-17 10:50
 */
public class FilePanel extends BaseTitlePanel implements ActionListener {

    /**
     * 文件选择器
     */
    private JFileChooser fileChooser;
    private JTextField textField;
    private JButton chooseBtn;

    public FilePanel(InDbPanel parentPanel) {
        super(parentPanel);
    }

    @Override
    protected String getPanelTitle() {
        return "入库文件";
    }


    @Override
    protected void render(JPanel container) {
        fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("入库文件选择");
        fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
        fileChooser.setDragEnabled(false);
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fileChooser.setMultiSelectionEnabled(false);

        // label
        JLabel label = new JLabel("路径：");
        container.add(label, BorderLayout.WEST);

        // text
        textField = new JTextField();
        textField.setEditable(false);
        container.add(textField, BorderLayout.CENTER);

        // button
        chooseBtn = new JButton("选择");
        chooseBtn.addActionListener(this);
        container.add(chooseBtn, BorderLayout.EAST);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Object target = e.getSource();
        if (target instanceof JButton) {
            if (target == chooseBtn) {
                // 弹出文件选择框
                fileChooser.showOpenDialog(getTopContainer());

                // 文件路径填入文本框中
                File selFile = fileChooser.getSelectedFile();
                if (selFile != null) {
                    textField.setText(selFile.getAbsolutePath());
                }
            }
        }
    }

    @Override
    public InDbGather gather() {
        InDbGather gather = new InDbGather();
        if (StringUtils.isNotBlank(textField.getText())) {
            gather.put("FILE", textField.getText());
            return gather;
        }

        PanelUtil.alert(getTopContainer(), "请选择需要入库的文件");
        return null;
    }

    @Override
    public void initByFile(FileGather gather) {
        initField("FILE", textField, gather);
    }
}